<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\UserRequest;
use App\Models\Permission;
use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;
use Auth;

class UsersController extends Controller
{
    public function index(Request $request)
    {
        return User::where(function($query) use ($request){
            if ($request->search){
                $search = '%'. $request->search .'%';
                $query->where('name', 'like', $search)->orWhere('email', 'like', $search)->orWhere('phone', 'like', $search);
            }
        })->paginate();
    }

    public function store(UserRequest $request)
    {
        $data = $request->only('name', 'email', 'is_lock', 'password', 'phone');
        $data['password'] = bcrypt($data['password']);

        $user = User::create($data);
        return $user;
    }

    public function edit(User $user)
    {
        return $user;
    }

    public function update(UserRequest $request, User $user)
    {
        // 超级用户
        if ($user->isSuper() && !$request->user('admin')){
            return $user;
        }

        $data = $request->only('name', 'email', 'is_lock', 'phone');
        if ($request->password){
            $data['password'] = bcrypt($request->password);
        }

        $user->update($data);
        return $user;
    }

    public function destroy(User $user)
    {
        $user->delete();

        // 关联角色、权限
        $user->roles()->detach();
        $user->permissions()->detach();
    }

    /**
     * 分配权限
     *
     * @param Request $request
     * @param Role $role
     * @return array
     */
    public function givePermission(Request $request, User $user)
    {
        if ($request->isMethod('post')){
            return $user->permissions()->sync($request->permissions);
        }
        return [
            'permissions' => Permission::get(['id', 'name', 'title', 'pid']),
            'myPermissions' => $user->permissions()->get()->pluck('id'),
        ];
    }

    /**
     * 分配角色
     *
     * @param Request $request
     * @param Role $role
     * @return array
     */
    public function giveRole(Request $request, User $user)
    {
        if ($request->isMethod('post')){
            return $user->roles()->sync($request->roles);
        }
        return [
            'roles' => Role::get(['id', 'name']),
            'myRoles' => $user->roles()->get()->pluck('id'),
        ];
    }




}